package com.niiwoo.civet.account.service.local;

import com.niiwoo.civet.account.dao.entity.ActivityOrder;
import com.niiwoo.civet.account.dao.entity.OldAccountBalance;
import com.niiwoo.civet.account.dao.mapper.OldAccountBalanceMapperExt;
import com.niiwoo.civet.account.dto.request.MarketingDubboRequestDTO;
import com.niiwoo.civet.account.enums.AccountPrizeExtendTypeEnum;
import com.niiwoo.civet.account.enums.AccountPrizeSourceFromEnum;
import com.niiwoo.civet.account.enums.AccountPrizeTypeIdEnum;
import com.niiwoo.tripod.lanmao.enums.UserRoleEnum;
import com.niiwoo.tripod.service.component.SnowflakeIdWorker;
import java.math.BigDecimal;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class OldAccountBalanceService {

    @Autowired
    OldAccountBalanceMapperExt oldAccountBalanceMapperExt;

    @Autowired
    MarketingLocalService marketingLocalService;

    @Autowired
    SnowflakeIdWorker snowflakeIdWorker;

    @Transactional(isolation = Isolation.READ_COMMITTED)
    public ActivityOrder prepare(String userId, String accountNo, UserRoleEnum userRole) {
        OldAccountBalance oldAccountBalance = oldAccountBalanceMapperExt.selectByPrimaryKeyForUpdate(userId);
        if (oldAccountBalance == null || oldAccountBalance.getRechargeStatus() != 0 || oldAccountBalance.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return null;
        }
        OldAccountBalance update = new OldAccountBalance();
        update.setUserId(userId);
        update.setRechargeStatus((byte) 1); // 处理中
        update.setRechargeTime(new Date());
        if (oldAccountBalanceMapperExt.updateByPrimaryKeySelective(update) <= 0) {
            return null;
        }
        MarketingDubboRequestDTO requestDTO = new MarketingDubboRequestDTO();
        requestDTO.setUserId(userId);
        requestDTO.setAmount(oldAccountBalance.getAmount());
        requestDTO.setAccountNo(accountNo);
        requestDTO.setOrderNo(snowflakeIdWorker.nextId());
        requestDTO.setUserRoleEnum(userRole);
        requestDTO.setPrizeTypeIdEnum(AccountPrizeTypeIdEnum.RETURN_OLD_ACCOUNT_BALANCE);
        requestDTO.setExtendTypeEnum(AccountPrizeExtendTypeEnum.DEFAULT);
        requestDTO.setSourceTypeEnum(AccountPrizeSourceFromEnum.FIRST_OPEN_ACCOUNT);
        return marketingLocalService.addSendCashOrder(requestDTO);
    }
}
